import { Role } from '@/utils/types.d';
import { FullscreenExitOutlined, FullscreenOutlined } from '@ant-design/icons';
import { ModalForm, ProFormSelect } from '@ant-design/pro-components';
import { Button, message } from 'antd';
import { throttle } from 'lodash';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import { queryCompanies } from '../SystemUser/service';
import Epayment from './Charts/Epayment';
import Overview from './Charts/Overview';
import ParkingIncome from './Charts/ParkingIncome';
import ParkingTraffic from './Charts/ParkingTraffic';
import CenterMap from './components/CenterMap';
import DailyIncome from './components/DailyIncome';
import DataCard from './components/DataCard';
import RealTimeMsg from './components/RealTimeMsg';
import TabHeader from './components/TabHeader';
import TimeHeader from './components/TimeHeader';
import WeekIncome from './components/WeekIncome';
import { dashInit, getDailyStatistic, getRealTimeParkingRecord } from './service';
import styles from './styles.less';
import type { DailyDataType, MsgObj } from './types.d';
import { handleRealTimeMsg } from './utils/utils';

const transferFenToYuan = (amount?: number) => {
  if (amount) {
    return Math.round(Math.abs(amount) / 100);
  }
  return 0;
};

const DEFAULT_DAILY: DailyDataType = {
  ownerName: '',
  parkingLotCount: 0,
  totalTraffic: 0,
  totalPlateCharged: 0,
  totalPlateFree: 0,
  totalPlateActual: 0,
  totalPlatePayable: 0,
  totalPayable: 0,
  totalAcutal: 0,
  totalPayment: 0,
  hourPlateActual: [],
  hourPlatePayable: [],
  hourTraffic: [],
  hourPlateCharged: [],
  hourMemberOrder: [],
  hourPayments: [],
};

const DashBoard = () => {
  const { initialState } = useModel('@@initialState');
  const currentUser = initialState?.currentUser;
  const selfName = currentUser?.userName || '';
  const [isFullScreen, setIsFullScreen] = useState<boolean>(false);
  const [wrapBox, setwrapBox] = useState<HTMLElement | null>(null);
  const [currDaily, setCurrDaily] = useState<DailyDataType>(DEFAULT_DAILY);
  const [modalVisible, setModalVisible] = useState<boolean>(false);
  const [realMsgs, setRealMsgs] = useState<MsgObj[]>([]);
  const [ownerId, setOwnerId] = useState(currentUser?.ownerId || '');

  const {} = currDaily;
  useEffect(() => {
    const tempBox = document.getElementById('homepagewrap');
    setwrapBox(tempBox);
  }, []);
  useEffect(() => {
    dashInit(ownerId).then((initData) => {
      if (initData.success) {
        const { dailyData, msgData } = initData.data;
        const handledMsg = handleRealTimeMsg(msgData);
        setCurrDaily(dailyData);
        setRealMsgs(handledMsg);
      } else {
        message.error({
          content: initData?.message || '获取失败',
          key: 'dashboard',
        });
        setCurrDaily(DEFAULT_DAILY);
      }
    });

    let timer01: NodeJS.Timeout;
    let timer02: NodeJS.Timeout;
    // eslint-disable-next-line prefer-const
    timer01 = setInterval(() => {
      getDailyStatistic()
        .then((res) => {
          if (res.success) {
            setCurrDaily(res.data);
          } else {
            message.error({
              content: res?.message || '更新数据失败',
              key: 'dashboard',
            });
          }
        })
        .catch((err) => {
          message.error({
            content: JSON.stringify(err) || '更新数据失败',
            key: 'dashboard',
          });
        });
    }, 1000 * 60 * 60);
    // eslint-disable-next-line prefer-const
    timer02 = setInterval(() => {
      getRealTimeParkingRecord().then((res) => {
        if (res.success) {
          const realTimeMsg = handleRealTimeMsg(res.data);
          setRealMsgs(realTimeMsg);
        } else {
          message.error({
            content: res?.message || '获取实时消息失败',
            key: 'dashboard',
          });
        }
      });
    }, 1000 * 60 * 5);
    return () => {
      clearInterval(timer01);
      clearInterval(timer02);
    };
  }, [ownerId]);
  // useEffect(() => {});
  if (wrapBox !== null) {
    const iniNumX = wrapBox.parentElement?.clientWidth || 1920;
    const iniNumY = wrapBox.parentElement?.clientHeight || 1080;
    wrapBox.style.transform = `scaleX(${iniNumX / 1920}) scaleY(${iniNumY / 1080})`;
    const handler = throttle(() => {
      const numX = wrapBox.parentElement?.clientWidth || 1920;
      const numY = wrapBox.parentElement?.clientHeight || 1080;
      wrapBox.style.transform = `scaleX(${numX / 1920}) scaleY(${numY / 1080})`;
    });
    window.addEventListener('resize', handler);
  }
  return (
    <div id="home" className={styles.homepage}>
      <div id="homepagewrap" className={styles.pagewrap}>
        <div
          className={styles.headerTitle}
          onClick={() => {
            setModalVisible(true);
          }}
          title={initialState?.currentUser?.role == Role.ADMIN ? '点击切换公司' : ''}
        >
          {currDaily.ownerName || '收费平台数据概览'}
        </div>
        <div className={styles.centerMap}>
          <CenterMap ownerId={ownerId} />
        </div>
        <div className={styles.headerLeft}>
          <TimeHeader username={selfName || ''} />
        </div>
        <div className={styles.headerRight}>
          <TabHeader />
        </div>
        <div className={styles.ratioLeft}>
          <DailyIncome
            payable={transferFenToYuan(currDaily.totalPlatePayable)}
            actual={transferFenToYuan(currDaily.totalPayment)}
          />
        </div>
        <div className={styles.ratioRight}>
          <WeekIncome traffic={currDaily.totalTraffic} lots={currDaily.parkingLotCount} />
        </div>
        <div className={styles.bottomBox}>
          <RealTimeMsg msgs={realMsgs} />
        </div>
        <div className={styles.leftTopCard}>
          <DataCard
            titleText="车场营收"
            dom={
              <Overview actual={currDaily.hourPlateActual} payable={currDaily.hourPlatePayable} />
            }
          />
        </div>
        <div className={styles.leftBottomCard}>
          <DataCard
            titleText="今日支付"
            dom={<Epayment epay={currDaily.hourPayments.map((item) => item / 100)} />}
          />
        </div>
        <div className={styles.rightTopCard}>
          <DataCard
            reverse
            titleText="停车订单"
            dom={
              <ParkingIncome
                orders={{
                  dayCharged: currDaily.totalPlateCharged,
                  dayFree: currDaily.totalPlateFree,
                }}
              />
            }
          />
        </div>
        <div className={styles.rightBottomCard}>
          <DataCard
            reverse
            titleText="今日车流量"
            dom={<ParkingTraffic traffic={currDaily.hourTraffic} />}
          />
        </div>
        <div className={styles.mask} />
        <div className={styles.fullscreen}>
          <Button
            title="全屏"
            type="link"
            style={{ opacity: 0.6 }}
            onClick={() => {
              const dom = document?.getElementById('home');
              if (dom && !isFullScreen) {
                if (dom.requestFullscreen) {
                  dom.requestFullscreen();
                  // @ts-ignore
                } else if (dom.webkitRequestFullScreen) {
                  // @ts-ignore
                  dom.webkitRequestFullScreen();
                  // @ts-ignore
                } else if (dom.mozRequestFullScreen) {
                  // @ts-ignore
                  dom.mozRequestFullScreen();
                  // @ts-ignore
                } else if (dom.msRequestFullscreen) {
                  // @ts-ignore
                  dom.msRequestFullscreen();
                } else {
                  message.warn({
                    content:
                      '当前浏览器不支持全屏浏览，请尝试以下浏览器中的某一个：Chrome、Firefox、Safari',
                    key: 'no-fullscreen',
                  });
                }
              } else if (document.exitFullscreen) {
                document.exitFullscreen();
                // @ts-ignore
              } else if (document.webkitExitFullscreen) {
                // @ts-ignore
                document.webkitExitFullscreen();
                // @ts-ignore
              } else if (document.mozCancelFullScreen) {
                // @ts-ignore
                document.mozCancelFullScreen();
                // @ts-ignore
              } else if (document.msExitFullscreen) {
                // @ts-ignore
                document.msExitFullscreen();
              } else {
                message.warn({
                  content: '如果无法点击退出全屏，请尝试点击键盘Esc键',
                  key: 'no-fullscreen',
                });
              }
              setIsFullScreen(!isFullScreen);
            }}
          >
            {isFullScreen ? <FullscreenExitOutlined /> : <FullscreenOutlined />}
          </Button>
        </div>
      </div>
      {currentUser?.role === Role.ADMIN && (
        <ModalForm<{
          ownerId: string;
        }>
          visible={modalVisible}
          title="请选择目标公司"
          layout="horizontal"
          labelCol={{ span: 6 }}
          wrapperCol={{ span: 14 }}
          width="35vw"
          modalProps={{
            destroyOnClose: true,
            onCancel: () => {
              setModalVisible(false);
            },
          }}
          onFinish={async (values) => {
            if (!values.ownerId) {
              message.error({ content: '请选择目标公司', key: 'dashboard' });
              return false;
            }
            const initData = await dashInit(values.ownerId);
            if (initData.success) {
              const { dailyData, msgData } = initData.data;
              const handledMsg = handleRealTimeMsg(msgData);
              setCurrDaily(dailyData);
              setRealMsgs(handledMsg);
              setOwnerId(values.ownerId);
            } else {
              message.error({
                content: initData?.message || '获取失败',
                key: 'dashboard',
              });
              setCurrDaily(DEFAULT_DAILY);
            }
            setModalVisible(false);
            return true;
          }}
        >
          <ProFormSelect
            name="ownerId"
            showSearch={true}
            placeholder="请选择首屏展示数据来源"
            debounceTime={300}
            request={(val) => queryCompanies(val?.keyWords || '', false)}
            label="所属公司"
          />
        </ModalForm>
      )}
    </div>
  );
};

export default DashBoard;
